'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { contentId, type, action, reason = '', adminId } = event;

  if (!contentId || !type || !action) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  const validActions = ['approved', 'rejected', 'published', 'pending_review', 'reviewed_approved', 'reviewed_rejected', 'hidden'];
  if (!validActions.includes(action)) {
    return {
      code: 400,
      msg: '审核动作不正确',
      data: null
    };
  }

  try {
    const contentCollection = db.collection('add-content');
    
    // 更新内容审核状态
    const updateData = {
      review_time: Date.now(),
      reviewer_action: action,
      reviewer_id: adminId || 'admin',
      last_modified: Date.now()
    };

    // 根据不同的审核动作设置状态
    if (action === 'approved' || action === 'reviewed_approved') {
      updateData.status = 'reviewed_approved';
    } else if (action === 'rejected' || action === 'reviewed_rejected') {
      if (!reason) {
        return {
          code: 400,
          msg: '拒绝审核需要填写理由',
          data: null
        };
      }
      updateData.status = 'reviewed_rejected';
      updateData.reject_reason = reason;
      updateData.review_reason = reason;
    } else if (action === 'hidden') {
      updateData.status = 'hidden';
      updateData.review_reason = reason || '内容已隐藏';
    } else {
      // 直接使用传入的状态
      updateData.status = action;
      if (reason) {
        updateData.review_reason = reason;
      }
    }

    const result = await contentCollection.doc(contentId).update(updateData);

    // 记录审核日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: type, // post, activity
      target_id: contentId,
      action: action,
      reason: reason,
      admin_id: adminId || 'admin',
      create_time: new Date()
    });

    // 审核通知处理
    if (action === 'approved') {
      console.log(`${type} ${contentId} 审核通过`);
    } else {
      console.log(`${type} ${contentId} 审核拒绝，理由：${reason}`);
    }

    return {
      code: 200,
      msg: '审核成功',
      data: {
        contentId: contentId,
        action: action,
        updated: result.updated
      }
    };
  } catch (error) {
    console.error('内容审核失败:', error);
    return {
      code: 500,
      msg: '审核失败',
      data: null
    };
  }
};
